import axios, { Method, AxiosResponse, AxiosRequestHeaders, AxiosRequestConfig } from 'axios'
import { SUCCESS_CODE, BASE_URL } from '@/config'
import { message, notification } from 'antd'

interface HttpRequest {
  url: string
  method: Method
  params?: any
  data?: any
  iserror?: boolean
  isBig?: boolean
}

interface Response<T> {
  status_code: number
  status: string
  message: string
  data: T
}
const service = axios.create()
service.interceptors.request.use(
  (config: any) => {
    if (window.navigator.onLine === false) {
      return Promise.reject('未连接到互联网')
    }
    if (window.sessionStorage.getItem('token')) {
      config.headers.Authorization = window.sessionStorage.getItem('token') || ''
      config.headers.mark = 1
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  (response: AxiosResponse) => {
    const res = response.data
    //@ts-ignore
    if (res.status_code !== SUCCESS_CODE && !(res instanceof Blob) && response.config.iserror) {
      if (res.status_code === 401) {
        // 无效的token
        window.localStorage.removeItem('token')
        window.location.replace('/#/login')
      } else {
        message.error(res.message)
      }
    }
    return response
  },

  (error) => {
    // token过期
    if (error.response?.status === 401) {
      notification.error({ message: '认证错误', description: '请重新登入后再试' })
    } else if (error.response?.status === 404) {
      notification.warning({ message: '404', description: '服务器丢了' })
    } else if (error.response?.status === 502 || error.message == 'Network Error') {
      notification.warning({ message: '错误', description: '网络异常' })
    } else if(error.message == 'timeout of 6000ms exceeded'){
      notification.warning({ message: '错误', description: '网络超时' })
    } else {
      notification.error({
        message: '错误',
        description: typeof error === 'object' ? error.message || error.response?.data.message : error
      })
    }
    return Promise.reject(error)
  }
)

export function HTTP<T>({ url, method, data, iserror = true, isBig = false }: HttpRequest): Promise<Response<T>> {
  const req = {
    url: BASE_URL + url,
    method: method || 'get',
    data: data,
    params: data,
    iserror: iserror,
    timeout: isBig ? undefined : 6000
  }

  if (req.method.toLowerCase() === 'post') {
    delete req.params
  } else {
    delete req.data
  }
  return service.request<Response<T>>(req).then((res: AxiosResponse) => res.data)
}
